package com.lh.controller;

import com.lh.entity.Goods;
import com.lh.entity.Image;
import com.lh.entity.User;
import com.lh.service.GoodsService;
import com.lh.service.ImageService;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: LuoHang
 * @Date: 2021/2/10 12:25
 * @Description
 */
@Controller
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private ImageService imageService;

    /**
     * 普通用户首页
     *
     * @return 视图模型
     */
    @RequestMapping("/main")
    public ModelAndView main() {
        ModelAndView modelAndView = new ModelAndView();
        List<Goods> clothingGoods = getGoodsByCategoryId(1);
        List<Goods> beautyGoods = getGoodsByCategoryId(2);
        List<Goods> bookGoods = getGoodsByCategoryId(3);
        List<Goods> electronicGoods = getGoodsByCategoryId(4);
        List<Goods> toyGoods = getGoodsByCategoryId(5);
        List<Goods> foodGoods = getGoodsByCategoryId(6);
        modelAndView.addObject("clothingGoods",clothingGoods);
        modelAndView.addObject("beautyGoods",beautyGoods);
        modelAndView.addObject("bookGoods",bookGoods);
        modelAndView.addObject("electronicGoods",electronicGoods);
        modelAndView.addObject("toyGoods",toyGoods);
        modelAndView.addObject("foodGoods",foodGoods);
        modelAndView.setViewName("main");
        return modelAndView;
    }

    /**
     * 获取商品列表页面
     *
     * @return 视图模型
     */
    @RequestMapping("/getGoodsList")
    public ModelAndView getGoodsList() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("merchant/goods_list");
        return modelAndView;
    }

    /**
     * 获取数据库中符合条件的商品信息
     *
     * @return JSON格式的数据
     */
    @RequestMapping("/getGoods")
    @ResponseBody
    public Map<String, Object> getGoods(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer limit) {
        User user = (User) request.getSession().getAttribute("user");
        String id = request.getParameter("id");
        String goodsName = request.getParameter("goodsName");
        String goodsStatus = request.getParameter("goodsStatus");
        String categoryId = request.getParameter("categoryId");
        String goodsDesc = request.getParameter("goodsDesc");
        //条件模糊查询的数据
        Map<String, Object> query = new HashMap<>(10);
        if ("商家".equals(user.getRole().getRoleName().trim())){
            query.put("userId",user.getId());
        }
        if (!StringUtils.isNullOrEmpty(id)) {
            query.put("id", Integer.valueOf(id));
        }
        if (!StringUtils.isNullOrEmpty(goodsName)) {
            query.put("goodsName", goodsName);
        }
        String test = "请选择";
        if (!StringUtils.isNullOrEmpty(goodsStatus) && !test.equals(goodsStatus)) {
            query.put("goodsStatus", goodsStatus);
        }
        if (!StringUtils.isNullOrEmpty(categoryId) && !test.equals(categoryId)) {
            query.put("categoryId", Integer.parseInt(categoryId));
        }
        if (!StringUtils.isNullOrEmpty(goodsDesc)) {
            query.put("goodsDesc", goodsDesc);
        }
        query.put("beginSize", (page - 1) * limit);
        query.put("limit", limit);

        //layui前端框架需要的数据
        Map<String, Object> map = new HashMap<>(3);
        map.put("code", 0);
        map.put("msg", "");
        map.put("data", goodsService.getGoods(query));
        map.put("count", goodsService.getCount(query));
        return map;
    }

    /**
     * 获取添加商品的页面
     *
     * @return 视图模型
     */
    @RequestMapping("/addGoodsHtml")
    public ModelAndView addGoodsHtml() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("merchant/goods_publish");
        return modelAndView;
    }

    /**
     * 添加商品到数据库
     *
     * @return 是否添加成功
     */
    @RequestMapping("/addGoods")
    @ResponseBody
    public Map<String, Object> addGoods(HttpServletRequest request) throws IOException {
        Integer userId = Integer.parseInt(request.getParameter("userId"));
        String goodsName = request.getParameter("goodsName");
        String goodsDesc = request.getParameter("goodsDesc");
        BigDecimal goodsPrice = new BigDecimal(request.getParameter("goodsPrice"));
        Integer goodsNum = Integer.parseInt(request.getParameter("goodsNum"));
        Integer categoryId = Integer.parseInt(request.getParameter("categoryId"));

        MultipartFile multipartFile = ((MultipartHttpServletRequest)request).getFile("goodsImg");

        Image image = new Image();
        String fileName = System.currentTimeMillis() + multipartFile.getOriginalFilename();
        image.setImgName(fileName);
        String path = "D:/java code/static/images/" + fileName;
        File file = new File(path);
        if (!file.exists()){
            if (file.mkdirs()){
                multipartFile.transferTo(file);
            }
        }
        String url = "/upload/file/" + fileName;
        image.setUrl(url);

        Goods goods = new Goods(null, goodsName, goodsDesc, goodsNum, goodsPrice, new Timestamp(System.currentTimeMillis()),
                url, 1, categoryId, userId, null);
        int count = goodsService.addGoods(goods);

        goods = goodsService.getGoodsAdd(userId);

        image.setGoodsId(goods.getId());
        imageService.upload(image);

        Map<String, Object> res = new HashMap<>(1);
        res.put("data", count > 0 ? "添加成功" : "添加失败");
        return res;
    }

    /**
     * 商品信息更新页面
     *
     * @return 视图模型
     */
    @RequestMapping("/goodsEditHtml")
    public ModelAndView goodsEditHtml(@RequestParam Integer id) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("goodsInfo", getGoodsById(id));
        modelAndView.setViewName("merchant/goods_edit");
        return modelAndView;
    }

    /**
     * 商品信息更新
     *
     * @param request 请求对象
     * @param goodsId 商品对应的id
     * @return 是否更新成功
     */
    @RequestMapping("/updateGoods")
    @ResponseBody
    public Map<String, Object> updateGoods(HttpServletRequest request, @RequestParam Integer goodsId) {
        System.out.println(goodsId);
        String goodsStatus = request.getParameter("goodsStatus");
        String goodsName = request.getParameter("goodsName");
        String goodsNum = request.getParameter("goodsNum");
        String goodsPrice = request.getParameter("goodsPrice");
        //String goodsImg = request.getParameter("goodsImg");
        String goodsDesc = request.getParameter("goodsDesc");
        String categoryId = request.getParameter("categoryId");
        Goods goods = getGoodsById(goodsId);
        Map<String, Object> updateInfo = new HashMap<>(8);
        updateInfo.put("id", goodsId);
        updateInfo.put("gmtModified", new Timestamp(System.currentTimeMillis()));

        if (!StringUtils.isNullOrEmpty(goodsStatus) && goods.getGoodsStatus() != Integer.parseInt(goodsStatus)) {
            updateInfo.put("goodsStatus", goodsStatus);
        }
        if (!StringUtils.isNullOrEmpty(goodsName) && !goodsName.equals(goods.getGoodsName())) {
            updateInfo.put("goodsName", goodsName);
        }
        if (!StringUtils.isNullOrEmpty(goodsNum) && !Integer.valueOf(goodsNum).equals(goods.getGoodsNum())) {
            updateInfo.put("goodsNum", goodsNum);
        }
        if (!StringUtils.isNullOrEmpty(goodsPrice) && !BigDecimal.valueOf(Double.parseDouble(goodsPrice)).equals(goods.getGoodsPrice())) {
            updateInfo.put("goodsPrice", goodsPrice);
        }
//        if (!StringUtils.isNullOrEmpty(goodsPrice) && !goodsImg.equals(goods.getGoodsImg())) {
//            updateInfo.put("goodsImg", goodsImg);
//        }
        if (!StringUtils.isNullOrEmpty(goodsDesc) && !goodsDesc.equals(goods.getGoodsDesc())) {
            updateInfo.put("goodsDesc", goodsDesc);
        }
        String test = "请选择";
        if (!StringUtils.isNullOrEmpty(categoryId) && !test.equals(categoryId) && Integer.parseInt(categoryId) != goods.getCategoryId()) {
            updateInfo.put("categoryId", categoryId);
        }
        int count = goodsService.updateGoods(updateInfo);
        Map<String, Object> res = new HashMap<>(1);
        res.put("data", count > 0 ? "修改成功" : "修改失败");
        return res;
    }

    /**
     * 批量下架
     *
     * @return 是否成功
     */
    @RequestMapping("/goodsDownMany")
    @ResponseBody
    public Map<String, Object> downMany(@RequestParam("ids[]") List<Integer> ids) {
        int count = 0;
        if (ids != null && ids.size() > 0) {
            count = goodsService.downMany(ids);
        }
        Map<String, Object> res = new HashMap<>(1);
        res.put("data", count > 0 ? "批量下架成功" : "批量下架失败");
        return res;
    }

    /**
     * 批量上架
     *
     * @return 是否成功
     */
    @RequestMapping("/goodsUpMany")
    @ResponseBody
    public Map<String, Object> upMany(@RequestParam("ids[]") List<Integer> ids) {
        int count = 0;
        if (ids != null && ids.size() > 0) {
            count = goodsService.upMany(ids);
        }
        Map<String, Object> res = new HashMap<>(1);
        res.put("data", count > 0 ? "批量上架成功" : "批量上架失败");
        return res;
    }

    @RequestMapping("/deleteGoodsById")
    @ResponseBody
    public Map<String, Object> deleteGoodsById(@RequestParam Integer id) {
        int count = goodsService.deleteGoodsById(id);
        Map<String, Object> res = new HashMap<>(1);
        res.put("data", count > 0 ? "删除成功" : "删除失败");
        return res;
    }

    /**
     * 批量删除
     *
     * @return 是否成功
     */
    @RequestMapping("/deleteGoodsByIds")
    @ResponseBody
    public Map<String, Object> deleteGoodsByIds(@RequestParam("ids[]") List<Integer> ids) {
        int count = 0;
        if (ids != null && ids.size() > 0) {
            count = goodsService.deleteGoodsByIds(ids);
        }
        Map<String, Object> res = new HashMap<>(1);
        res.put("data", count > 0 ? "批量删除成功" : "批量删除失败");
        return res;
    }

    /**
     * 上架商品列表
     *
     * @return 视图模型
     */
    @RequestMapping("/getGoodsUpList")
    public ModelAndView getGoodsUpList() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("merchant/goodsUp_list");
        return modelAndView;
    }

    /**
     * 下架商品列表
     *
     * @return 视图模型
     */
    @RequestMapping("/getGoodsDownList")
    public ModelAndView getGoodsDownList() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("merchant/goodsDown_list");
        return modelAndView;
    }

    /**
     * 前台首页之更多商品展示
     *
     * @param request 请求对象
     * @param page    当前页
     * @param limit   每页显示的条数
     * @return 视图模型
     */
    @RequestMapping("/readMoreGoods")
    public ModelAndView readMoreGoods(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer limit) {
        String goodsName = request.getParameter("desc");
        String categoryId = request.getParameter("categoryId");
        ModelAndView modelAndView = new ModelAndView();
        Map<String, Object> map = new HashMap<>(5);
        if (!StringUtils.isNullOrEmpty(categoryId)) {
            map.put("categoryId", Integer.valueOf(categoryId));
        }
        map.put("beginSize", (page - 1) * limit);
        map.put("limit", limit);
        map.put("goodsStatus", 1);
        map.put("goodsName", goodsName);
        List<Goods> goods = goodsService.getGoodsByTime(map);
        modelAndView.addObject("goods", goods);
        modelAndView.setViewName("readMoreGoods");
        modelAndView.addObject("desc",goodsName);
        return modelAndView;
    }

    /**
     * 商品详情页
     *
     * @param id 商品对应的id
     * @return 视图模型
     */
    @RequestMapping("/goodsDetail")
    public ModelAndView goodsDetail(@RequestParam Integer id){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("goodInfo",goodsService.getGoodsById(id));
        modelAndView.setViewName("goods_detail");
        return modelAndView;
    }

    @RequestMapping("/getMainQuery")
    public ModelAndView getMainQuery(@RequestParam String desc){
        ModelAndView modelAndView = new ModelAndView();
        Map<String,Object> map = new HashMap<>(2);
        map.put("goodsName",desc);
        map.put("beginSize",0);
        map.put("limit",10);
        List<Goods> goods = goodsService.getGoods(map);
        modelAndView.addObject("goods", goods);
        modelAndView.setViewName("readMoreGoods");
        modelAndView.addObject("desc",desc);
        return modelAndView;
    }

    /**
     * 分类获取最新上架的商品
     *
     * @param id 分类id
     * @return 商品最新上架前四的商品集合
     */
    private List<Goods> getGoodsByCategoryId(Integer id){
        Map<String,Object> map = new HashMap<>(3);
        map.put("categoryId",id);
        map.put("beginSize",0);
        map.put("limit",4);
        return goodsService.getGoodsByTime(map);
    }

    /**
     * 通过ID查询到指定商品信息
     *
     * @param id 对应id
     * @return 对应商品对象
     */
    private Goods getGoodsById(Integer id) {
        return goodsService.getGoodsById(id);
    }
}
